package com.streamer.app

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.camera2.CameraCharacteristics
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alivc.live.pusher.AlivcLivePusher
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.button.MaterialButton
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.streamer.app.adapter.DanmakuAdapter
import com.streamer.app.adapter.EmojiAdapter
import com.streamer.app.adapter.ProductListAdapter
import com.streamer.app.adapter.ProductPagerAdapter
import com.streamer.app.adapter.UserListAdapter
import com.streamer.app.bean.LiveBean
import com.streamer.app.bean.LoginBean
import com.streamer.app.bean.MessageBean
import com.streamer.app.model.User
import com.streamer.app.model.UserRole
import com.streamer.app.utils.BottomSheetUtils
import com.streamer.app.utils.DialogUtils
import com.streamer.app.utils.DialogUtils.showAnnouncementDialog
import com.streamer.app.utils.MqttManager
import com.streamer.app.utils.ToastUtil
import com.streamer.app.utils.UserManager
import com.streamer.app.utils.UserManager.getLocalUser
import com.streamer.app.utils.Utils
import com.streamer.app.utils.api.ViewModel
import com.streamer.app.utils.camera2.PhoneCameraManager
import com.streamer.app.model.MyViewModel
import androidx.lifecycle.ViewModelProvider
import com.streamer.app.bean.GiftData
import com.streamer.app.bean.LiveStats
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.random.Random


class LiveStreamActivity : BaseActivity(), MqttManager.MessageCallback {

    // 开播前的控件
    private lateinit var btnStartBroadcast: MaterialButton
    private lateinit var topUserSection: ViewGroup
    private lateinit var bottomControlPanel: LinearLayout

    // 直播结束后的控件
    private lateinit var tvTitleEnded: TextView
    private lateinit var centerEndedContent: LinearLayout
    private lateinit var llLiveNotice: LinearLayout
    private lateinit var llGift: LinearLayout
    private lateinit var ivClock: ImageView
    private lateinit var ivGiftIcon: ImageView
    private lateinit var tvGiftName: TextView
    private lateinit var ivAvatar: ImageView
    private lateinit var tvMessage: TextView
    private lateinit var tvStreamerName: TextView
    private lateinit var tvViewerCount: TextView
    private lateinit var tvStreamerNumber: TextView


    private lateinit var tvDisableCount: TextView
    private lateinit var tvBackName: TextView

    // 共用控件
    private lateinit var ivClose: ImageView
    private lateinit var ivMic: ImageView
    private lateinit var ivRecord: ImageView
    private lateinit var ivExitClose: ImageView

    // 底部弹窗
    private var bottomSheetDialog: BottomSheetDialog? = null
    private var userListDialog: BottomSheetDialog? = null
    private var productListDialog: BottomSheetDialog? = null
    private var searchDialog: BottomSheetDialog? = null

    // 自定义表情面板（新方案）
    private var emojiContainer: View? = null
    private var isEmojiPanelVisible = false

    // 摄像头相关
    private lateinit var cameraPreviewContainer: FrameLayout
    private lateinit var cameraOffBackground: LinearLayout
    private var isLiveStreaming = false
    private var isCameraEnabled = true // 跟踪摄像头开关状态
    private lateinit var surfaceView: SurfaceView
    private lateinit var surfaceHolder: SurfaceHolder
    private var pendingStartPush: Boolean = false
    private val CAMERA_PERMISSION_REQUEST = 100

    // 风险提示文本相关
    private lateinit var riskAlertTextView: TextView
    private var riskAlertScrollJob: Job? = null
    private var riskAlertText = ""
    private var displayMode = 2 // 1:底部循环滚动, 2:全屏滚动
    private var displayFontSize = 14f
    private var displayFontColour = "#FFFFFF"
    private var displayScrollSpeed = 30 // 滚动速度(毫秒)
    private var displayTransparency = 0.8f // 透明度
    private lateinit var rvDanmaku: RecyclerView
    private lateinit var danmakuAdapter: DanmakuAdapter
    private lateinit var etSend: EditText

    // 阿里云直播推流相关
    val mAlivcLivePusher = AlivcLivePusher()
    private var currentPage = 1
    private var pageSize = 99
    private var mLiveUserCount: LoginBean? = null
    private var currentState = State.PRE_LIVE // 当前状态
    private var viewMode = ViewModel()
    private lateinit var myViewModel: MyViewModel
    private lateinit var ivViewer1: ImageView
    private lateinit var tabOnSale: TextView
    private lateinit var tabOffShelf: TextView
    private lateinit var ivViewer2: ImageView
    private lateinit var ivViewer3: ImageView

    // MQTT相关
    private lateinit var mqttManager: MqttManager

    // 点赞相关
    private var consecutiveLikeClicks = 0
    private var likeHandler = Handler()
    private val LIKE_DELAY = 1000L // 1秒延迟
    private var queryJob: Job? = null

    enum class State {
        NO_START_LIVE, PRE_LIVE,    // 开播前
        LIVE_ENDED   // 直播结束
    }

    private var mliveData: LiveBean? = null

    companion object {
        const val EXTRA_LIVE_STATE = "live_state"
        const val STATE_PRE_LIVE = "pre_live"
        const val STATE_LIVE_ENDED = "live_ended"
    }

    private val prefs by lazy { getSharedPreferences("switch_prefs", MODE_PRIVATE) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live_stream_simple)

        // 从Intent获取状态参数
        val stateParam = intent.getStringExtra(EXTRA_LIVE_STATE) ?: STATE_PRE_LIVE
        currentState = when (stateParam) {
            STATE_LIVE_ENDED -> State.LIVE_ENDED
            else -> State.PRE_LIVE
        }

        // 初始化 MyViewModel
        myViewModel = ViewModelProvider(this)[MyViewModel::class.java]

        initViews()
        setupListeners()
        setupTopPadding()
        setupBottomPadding()
        updateUIForState(currentState)
        setupKeyboardHandling()

        // 监听 MyViewModel 的数据变化
        observeMyViewModel()
    }

    private fun observeMyViewModel() {
        // 监听售卖中商品数量变化
        myViewModel.message.observe(this) { count ->
            Log.d("LiveStreamActivity", "MyViewModel message 变化: $count")
            if (::tabOnSale.isInitialized) {
                tabOnSale.text = "售卖中 ($count)"
            }
        }

        // 监听已下架商品数量变化
        myViewModel.message2.observe(this) { count ->
            Log.d("LiveStreamActivity", "MyViewModel message2 变化: $count")
            if (::tabOffShelf.isInitialized) {
                tabOffShelf.text = "已下架 ($count)"

            }
        }
    }

    private fun initViews() {

        viewMode.getLiveInfo()

        llGift = findViewById(R.id.llGift)
        ivGiftIcon = findViewById(R.id.ivGiftIcon)
        tvGiftName = findViewById(R.id.tvGiftName)
        ivViewer1 = findViewById(R.id.iv_viewer_1)
        ivViewer2 = findViewById(R.id.iv_viewer_2)
        ivViewer3 = findViewById(R.id.iv_viewer_3)
        ivExitClose = findViewById(R.id.iv_exit_close)
        viewMode.LiveInfoDataLV.observe(this@LiveStreamActivity) {
            if (it != null) {
                mliveData = it
            }
        }
        viewMode.LiveInfoLV.observe(this@LiveStreamActivity) {
            if (it != null) {
                mliveData = it
                // 处理风险提示文本 - 优先使用 riskAlertContent
                var riskContent: String? = null
                // 首先尝试从 riskAlertContent 获取
                riskContent = it.riskAlertContent as? String
                // 如果 riskAlertContent 为空，尝试从 liveCommonConfig 中获取
                if (riskContent.isNullOrEmpty() && it.liveCommonConfig != null) {
                    try {
                        val configStr = it.liveCommonConfig.toString()
                        // 尝试解析为 JSON
                        val jsonObject = org.json.JSONObject(configStr)
                        riskContent = jsonObject.optString("riskAlertContent")
                    } catch (e: Exception) {
                    }
                }

                // 如果还是没有，尝试从 liveConfig 中获取
                if (riskContent.isNullOrEmpty()) {
                    riskContent = it.liveConfig?.riskAlertContent
                    Log.d("RiskAlert", "riskContent from liveConfig: $riskContent")
                }


                if (riskContent != null && riskContent.isNotEmpty()) {
                    riskAlertText = riskContent
                }

                // 应用 liveCommonConfig 中的配置
                if (it.liveCommonConfig != null) {
                    try {
                        // 使用反射获取 liveCommonConfig 对象的属性
                        val configClass = it.liveCommonConfig.javaClass
                        Log.d("RiskAlert", "liveCommonConfig class: ${configClass.simpleName}")

                        // 获取 displayMode
                        val displayModeField = configClass.getDeclaredField("displayMode")
                        displayModeField.isAccessible = true
                        val modeValue = displayModeField.get(it.liveCommonConfig)
                        displayMode = (modeValue as? Number)?.toInt() ?: 2
                        Log.d("RiskAlert", "Set displayMode from liveCommonConfig: $displayMode")

                        // 获取 displayFontSize
                        val fontSizeField = configClass.getDeclaredField("displayFontSize")
                        fontSizeField.isAccessible = true
                        val fontSizeValue = fontSizeField.get(it.liveCommonConfig)
                        displayFontSize = (fontSizeValue as? Number)?.toFloat() ?: 16f
                        Log.d(
                            "RiskAlert",
                            "Set displayFontSize from liveCommonConfig: $displayFontSize"
                        )

                        // 获取 displayFontColour
                        val fontColourField = configClass.getDeclaredField("displayFontColour")
                        fontColourField.isAccessible = true
                        val fontColourValue = fontColourField.get(it.liveCommonConfig)
                        displayFontColour = fontColourValue as? String ?: "#FFFFFF"

                        // 获取 displayScrollSpeed
                        val scrollSpeedField = configClass.getDeclaredField("displayScrollSpeed")
                        scrollSpeedField.isAccessible = true
                        val scrollSpeedValue = scrollSpeedField.get(it.liveCommonConfig)
                        displayScrollSpeed = (scrollSpeedValue as? Number)?.toInt() ?: 50


                        // 获取 displayTransparency
                        val transparencyField = configClass.getDeclaredField("displayTransparency")
                        transparencyField.isAccessible = true
                        val transparencyValue = transparencyField.get(it.liveCommonConfig)
                        displayTransparency =
                            (transparencyValue as? Number)?.toFloat()?.div(100f) ?: 0.8f


                    } catch (e: Exception) {
                        Log.d(
                            "RiskAlert", "Failed to get liveCommonConfig properties: ${e.message}"
                        )
                    }
                }

                // 确保 displayMode 是有效值
                if (displayMode != 1 && displayMode != 2) {
                    displayMode = 2 // 默认使用全屏滚动模式
                }

                // 如果 liveCommonConfig 中没有配置，尝试从 liveConfig 中获取
                if (displayMode == 1 && displayFontSize == 16f && displayFontColour == "#FFFFFF") {
                    it.liveConfig?.let { liveConfig ->
                        liveConfig.displayMode?.let { mode ->
                            displayMode = mode
                        }
                        liveConfig.displayFontSize?.let { size ->
                            displayFontSize = size.toFloat()
                        }
                        liveConfig.displayFontColour?.let { color ->
                            displayFontColour = color
                        }
                        liveConfig.displayScrollSpeed?.let { speed ->
                            displayScrollSpeed = speed
                        }
                        liveConfig.displayTransparency?.let { transparency ->
                            displayTransparency = transparency / 100f
                        }
                    }
                }

                updateRiskAlertDisplay()

                /**透明度*/
                viewMode.liveUserCount(it?.id.toString())
                //获取直播间历史评论
                viewMode.messageHistory(it?.id.toString())

                // 在获取到直播数据后设置MQTT连接
                setupMqtt()

//                直播状态 0:未开始, 1:直播中, 2:已结束

                when (it.useState) {
                    0 -> {
                        currentState = State.NO_START_LIVE
                    }

                    1 -> {
                        currentState = State.PRE_LIVE
                        startLiveStream()

                    }

                    2 -> {

                        currentState = State.LIVE_ENDED
                        updateUIForState(currentState)
                    }
                }
            }
        }
        ivExitClose.setOnClickListener {
            val intent = Intent(this@LiveStreamActivity, LoginActivity::class.java)
            startActivity(intent)
            UserManager.clearData()
            finish()
        }
        // 初始化弹幕列表
        rvDanmaku = findViewById(R.id.rv_danmaku)
        danmakuAdapter = DanmakuAdapter(mutableListOf())
        rvDanmaku.apply {
            layoutManager = LinearLayoutManager(this@LiveStreamActivity).apply {
                stackFromEnd = true
            }
            adapter = danmakuAdapter
        }
        // 历史消息/新消息观察
        viewMode.MessageListLV.observe(this) { result ->
            result?.data?.let { list ->
                danmakuAdapter.setAll(list)
                rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
            }
        }

        // 开播前控件
        btnStartBroadcast = findViewById(R.id.btn_start_broadcast)
        topUserSection = findViewById(R.id.top_user_section)
        bottomControlPanel = findViewById(R.id.bottom_control_panel)

        // 直播结束控件
        tvTitleEnded = findViewById(R.id.tv_title_ended)
        centerEndedContent = findViewById(R.id.center_ended_content)
        ivClock = findViewById(R.id.iv_clock)
        ivAvatar = findViewById(R.id.iv_streamer_avatar)
        tvMessage = findViewById(R.id.tv_message)
        tvStreamerName = findViewById(R.id.tv_streamer_name)
        tvViewerCount = findViewById(R.id.tv_viewer_count)
        tvStreamerNumber = findViewById(R.id.tv_streamer_number)
        llLiveNotice = findViewById(R.id.llLiveNotice)
        llLiveNotice = findViewById(R.id.llLiveNotice)

        // 摄像头预览容器
        cameraPreviewContainer = findViewById(R.id.camera_preview_container)
        cameraOffBackground = findViewById(R.id.camera_off_background)

        // 初始化SurfaceView - 使用普通SurfaceView实现全屏显示
        surfaceView = SurfaceView(this)
        surfaceHolder = surfaceView.holder

        // 初始化风险提示文本 - 使用 XML 中定义的 TextView
        riskAlertTextView = findViewById(R.id.tv_risk_alert)

        // 设置默认文本和显示
        riskAlertText = "测试文本"
        updateRiskAlertDisplay()

        // 发送输入框 IME 回车发送
        etSend = findViewById(R.id.etSend)



        etSend.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                val text = etSend.text?.toString()?.trim().orEmpty()
                if (text.isNotEmpty()) {
                    viewMode.send(text, mliveData?.id.toString())
                    rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
                    etSend.setText("")
                }
                true
            } else {
                false
            }
        }
        surfaceHolder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                // Surface创建后，若有等待启动，则开始预览与推流
                if (pendingStartPush && !isDestroyed && !isFinishing) {
                    try {
                        mAlivcLivePusher.startPreview(surfaceView)
                        if (!mliveData?.pushLiveUrl.isNullOrEmpty()) {
                            mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    } finally {
                        pendingStartPush = false
                    }
                }
            }

            override fun surfaceChanged(
                holder: SurfaceHolder, format: Int, width: Int, height: Int
            ) {
                // 交由pusher处理，无需手动reconfigure
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                // 交由pusher停止预览与销毁
            }
        })

        // 将SurfaceView添加到容器中
        cameraPreviewContainer.addView(surfaceView)

        // 设置SurfaceView的布局参数，实现全屏显示
        val layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        )
        layoutParams.gravity = Gravity.CENTER
        surfaceView.layoutParams = layoutParams

        // 设置SurfaceView的ZOrder，确保摄像头预览在底层，不遮挡其他控件
        surfaceView.setZOrderOnTop(false)
        surfaceView.setZOrderMediaOverlay(false)
        surfaceView.elevation = 0f // 确保 SurfaceView 在底层

        // 根据固定比例(16:9)调整Surface的实际缓冲区尺寸，避免拉伸
        surfaceView.addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ ->
            if (!isLiveStreaming) {
                val width = right - left
                val height = bottom - top
                adjustSurfaceFixedSize(width, height)
            }
        }

        // 共用控件
        ivClose = findViewById(R.id.iv_close)
        ivMic = findViewById(R.id.iv_mic)
        ivRecord = findViewById(R.id.iv_record)

        // 观众头像列表点击事件
        val llListAudienceAvatar = findViewById<LinearLayout>(R.id.llListAudienceAvatar)
        llListAudienceAvatar.setOnClickListener {
            showUserListDialog()
        }
        viewMode.pageQuery(mliveData?.id.toString(), pageSize, currentPage)


        llLiveNotice.setOnClickListener {
            viewMode.getLastLiveNotice()
        }
        viewMode.LiveNoteTips.observe(this@LiveStreamActivity) {
            if (it != null) {
                showAnnouncementDialog(this@LiveStreamActivity, "公告", it.toString())
            }
        }

        ivAvatar.apply {
            Glide.with(this).load(getLocalUser()?.avatar).circleCrop().into(this)

            tvStreamerName.text = getLocalUser()?.nickName
        }
        viewMode.LiveUserCountLV.observe(this@LiveStreamActivity) {
            if (it != null) {
                mLiveUserCount = it

                if (::tvDisableCount.isInitialized) {
                    // 已经初始化，可以安全使用
                    tvDisableCount.text = "禁言名单(${mLiveUserCount?.disableCount.toString()})"
                }
                if (::tvBackName.isInitialized) {
                    tvBackName.text = "踢出房间名单(${mLiveUserCount?.defriendCount.toString()})"
                }
                tvViewerCount.text = it.liveCount.toString() + "人"
                tvStreamerNumber.text = it.popularity.toString() + "点赞"
            }
        }


    }

    private fun setupListeners() {
        btnStartBroadcast.setOnClickListener {
            // 检查MQTT连接状态
            if (::mqttManager.isInitialized && mqttManager.isConnected()) {
                viewMode.startLive()
                startLiveStream()
            } else {
                val random6Digit = Random.nextInt(100000, 1000000)
                // 连接MQTT
                if (::mqttManager.isInitialized) {
                    mqttManager.connect(
                        this@LiveStreamActivity,
                        "${mliveData?.liveRoomNo + "," + mliveData?.id + "," + getLocalUser()?.id + ",5" + "," + random6Digit}"
                    ) { success, message ->
                        runOnUiThread {
                            if (success) {
                                viewMode.startLive()
                                startLiveStream()
                            }
                        }
                    }
                } else {
                    Log.e("LiveStreamActivity", "MQTT manager not initialized")
                }
            }
        }

        ivClose.setOnClickListener {
            DialogUtils.showEndLiveMuteConfirmDialog(this@LiveStreamActivity, {
                viewMode.endLive()

            })
        }
        viewMode.EndLiveLV.observe(this@LiveStreamActivity) {
//            endLiveStream()
//            viewMode.getLiveInfo()
            val intent = Intent(this@LiveStreamActivity, LoginActivity::class.java)
            startActivity(intent)
            UserManager.clearData()
            finish()
        }

        ivMic.setOnClickListener {
            showBottomSheet()
        }


        viewMode.pageQuery(mliveData?.id.toString(), pageSize, currentPage)


        // 点赞按钮动画
        ivRecord.setOnClickListener {
            Utils.playLikeAnimation(ivRecord)
            consecutiveLikeClicks++

            // 取消之前的延迟任务
            likeHandler.removeCallbacksAndMessages(null)

            // 设置1秒后发送点赞请求
            likeHandler.postDelayed({
                if (consecutiveLikeClicks > 0) {
                    viewMode.like(consecutiveLikeClicks.toString())
                    consecutiveLikeClicks = 0 // 重置计数器
                }
            }, LIKE_DELAY)
        }

        viewMode.LikeLiveLV.observe(this@LiveStreamActivity) {
            ToastUtil.toastShortMessage("点赞成功！")
        }
        // emoji按钮点击事件
        val tvIcon = findViewById<TextView>(R.id.tvIcon)
        tvIcon.setOnClickListener {
            toggleEmojiPanel()
        }

        // 美颜按钮点击事件
        val ivBeauty = findViewById<View>(R.id.iv_beauty)
        ivBeauty.setOnClickListener {
            showProductListDialog()
        }


    }


    private fun startLiveStream() {
        try {
            // 检查摄像头权限
            if (!checkCameraPermission()) {
                requestCameraPermission()
                return
            }
            // 检查麦克风权限
            if (!checkMicrophonePermission()) {
                requestCameraPermission()
                return
            }

            // 显示摄像头预览
            cameraPreviewContainer.visibility = View.VISIBLE

            // 确保 TextView 也可见
            riskAlertTextView.visibility = View.VISIBLE
            riskAlertTextView.bringToFront()

            // 隐藏开播按钮
            btnStartBroadcast.visibility = View.GONE
            ivExitClose.visibility = View.GONE

            // 检查摄像头开关状态，如果关闭则显示背景
            if (!isCameraEnabled) {
                cameraOffBackground.visibility = View.VISIBLE
            }

            mAlivcLivePusher.init(this@LiveStreamActivity, mAlivcLivePushConfig);

            // 暂时注释掉推流监听器，避免编译错误

            isLiveStreaming = true

            // Surface未就绪时，延后到surfaceCreated再启动预览与推流
            val surface = surfaceHolder.surface
            if (surface == null || !surface.isValid) {
                pendingStartPush = true
                return
            }
            // 先启动预览，确保摄像头正常工作
            Log.d("LiveStream", "开始启动摄像头预览")
            mAlivcLivePusher.startPreview(surfaceView)
            // 开始推流（稍作延时，避免紧邻预览导致黑屏）
            surfaceView.postDelayed({
                try {
                    mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }, 150)

            // 预览与相机控制由阿里云pusher管理，无需手动打开摄像头
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "开启直播失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun endLiveStream() {
        try {
            if (isLiveStreaming) {


                // 停止阿里云直播推流
                mAlivcLivePusher?.stopPreview()
                mAlivcLivePusher?.stopPush()
                mAlivcLivePusher?.destroy()

                // 隐藏摄像头预览
                cameraPreviewContainer.visibility = View.GONE

                // 显示开播按钮
                btnStartBroadcast.visibility = View.VISIBLE

                isLiveStreaming = false
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        // 发送直播结束状态到MQTT
        publishLiveStatus("ended")

        currentState = State.LIVE_ENDED
        updateUIForState(currentState)
        Toast.makeText(this, "直播已结束", Toast.LENGTH_SHORT).show()
    }

    private fun updateUIForState(state: State) {
        when (state) {
            State.NO_START_LIVE -> {

            }

            State.PRE_LIVE -> {
                // 显示开播前的UI
                btnStartBroadcast.visibility = View.VISIBLE
                topUserSection.visibility = View.VISIBLE
                bottomControlPanel.visibility = View.VISIBLE
                llLiveNotice.visibility = View.VISIBLE

                // 隐藏结束状态的UI
                tvTitleEnded.visibility = View.GONE
                centerEndedContent.visibility = View.GONE
            }

            State.LIVE_ENDED -> {
                // 隐藏开播前的UI
                btnStartBroadcast.visibility = View.GONE
                topUserSection.visibility = View.GONE
                bottomControlPanel.visibility = View.GONE
                llLiveNotice.visibility = View.GONE

                // 显示结束状态的UI
                tvTitleEnded.visibility = View.GONE
                centerEndedContent.visibility = View.VISIBLE
                ivExitClose.visibility = View.VISIBLE
            }
        }
//        endLiveStream()
    }

    private fun setupTopPadding() {
        // 为开播前的顶部用户区域设置动态间距
        ViewCompat.setOnApplyWindowInsetsListener(topUserSection) { view, insets ->
            val statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top

            // 自定义顶部间距：基础间距 + 状态栏高度
            val basePadding = 16 // dp
            val basePaddingPx = (basePadding * resources.displayMetrics.density).toInt()
            val totalTopPadding = basePaddingPx + statusBarHeight

            view.setPadding(
                view.paddingLeft, totalTopPadding, view.paddingRight, view.paddingBottom
            )

            insets
        }

        // 为直播结束状态的标题设置动态间距
        ViewCompat.setOnApplyWindowInsetsListener(tvTitleEnded) { view, insets ->
            val statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top

            // 自定义顶部间距：基础间距 + 状态栏高度
            val basePadding = 16 // dp
            val basePaddingPx = (basePadding * resources.displayMetrics.density).toInt()
            val totalTopPadding = basePaddingPx + statusBarHeight

            view.setPadding(
                view.paddingLeft, totalTopPadding, view.paddingRight, view.paddingBottom
            )

            insets
        }
    }

    private fun setupBottomPadding() {
        // 设置WindowInsets监听来获取系统导航栏高度
        ViewCompat.setOnApplyWindowInsetsListener(bottomControlPanel) { view, insets ->
            val navigationBarHeight =
                insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom

            // 自定义底部间距：基础间距 + 导航栏高度
            val basePadding = 32 // dp
            val basePaddingPx = (basePadding * resources.displayMetrics.density).toInt()
            val totalBottomPadding = basePaddingPx + navigationBarHeight

            // 设置底部间距
            view.setPadding(
                view.paddingLeft, view.paddingTop, view.paddingRight, totalBottomPadding
            )

            insets
        }
    }

    private fun showBottomSheet() {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = BottomSheetDialog(this)
            val bottomSheetView = layoutInflater.inflate(R.layout.bottom_sheet_more, null)
            bottomSheetDialog?.setContentView(bottomSheetView)

            // 设置弹窗属性
            bottomSheetDialog?.setCancelable(true)
            bottomSheetDialog?.setCanceledOnTouchOutside(true)

            // 设置底部弹窗的控件监听
            setupBottomSheetListeners(bottomSheetView)
        }

        bottomSheetDialog?.show()
    }

    private fun setupBottomSheetListeners(view: View) {
        // 关闭按钮
        view.findViewById<ImageView>(R.id.iv_close_bottom_sheet).setOnClickListener {
            bottomSheetDialog?.dismiss()
        }

        // 摄像头前后切换按钮
        val tvFront = view.findViewById<TextView>(R.id.tvFront)
        val tvAfter = view.findViewById<TextView>(R.id.tvAfter)
        val llmore = view.findViewById<View>(R.id.llmore)
        llmore.visibility = View.GONE
        // 默认选中前置摄像头
        tvFront.background = getDrawable(R.drawable.view_select_on)
        tvFront.setTextColor(getColor(R.color.white))
        tvAfter.background = getDrawable(R.drawable.view_select_off)
        tvAfter.setTextColor(getColor(R.color.gray))

        tvFront.setOnClickListener {
            // 选中前摄像头
            tvFront.background = getDrawable(R.drawable.view_select_on)
            tvFront.setTextColor(getColor(R.color.white))
            tvAfter.background = getDrawable(R.drawable.view_select_off)
            tvAfter.setTextColor(getColor(R.color.gray))
            switchCamera("1") // 前置摄像头
            Toast.makeText(this, "切换到前置摄像头", Toast.LENGTH_SHORT).show()
        }

        tvAfter.setOnClickListener {
            // 选中后摄像头
            tvAfter.background = getDrawable(R.drawable.view_select_on)
            tvAfter.setTextColor(getColor(R.color.white))
            tvFront.background = getDrawable(R.drawable.view_select_off)
            tvFront.setTextColor(getColor(R.color.gray))
            switchCamera("0") // 后置摄像头
            Toast.makeText(this, "切换到后置摄像头", Toast.LENGTH_SHORT).show()
        }

        // 摄像头切换开关
        view.findViewById<SwitchCompat>(R.id.switch_camera)
            .setOnCheckedChangeListener { _, isChecked ->
                try {
                    if (isLiveStreaming && true) {
                        if (isChecked) {
                            // 开启摄像头预览
                            try {
                                mAlivcLivePusher.startPreview(surfaceView)
                                // 更新状态并隐藏摄像头关闭背景
                                isCameraEnabled = true
                                cameraOffBackground.visibility = View.GONE
                                Toast.makeText(this, "摄像头开启", Toast.LENGTH_SHORT).show()
                                Log.d("LiveStreamActivity", "Camera enabled")
                            } catch (e: Exception) {
                                Log.e("LiveStreamActivity", "Failed to start camera: ${e.message}")
                                Toast.makeText(this, "摄像头开启失败", Toast.LENGTH_SHORT).show()
                            }
                        } else {
                            // 停止摄像头预览
                            try {
                                mAlivcLivePusher.stopPreview()
                                // 更新状态并显示摄像头关闭背景
                                isCameraEnabled = false
                                cameraOffBackground.visibility = View.VISIBLE
                                Toast.makeText(this, "摄像头关闭", Toast.LENGTH_SHORT).show()
                                Log.d("LiveStreamActivity", "Camera disabled")
                            } catch (e: Exception) {
                                Log.e("LiveStreamActivity", "Failed to stop camera: ${e.message}")
                                Toast.makeText(this, "摄像头关闭失败", Toast.LENGTH_SHORT).show()
                            }
                        }
                    } else {
                        Toast.makeText(this, "请先开始直播", Toast.LENGTH_SHORT).show()
                        Log.w("LiveStreamActivity", "Cannot control camera: not live streaming")
                    }
                } catch (e: Exception) {
                    Log.e("LiveStreamActivity", "Error controlling camera: ${e.message}")
                    Toast.makeText(this, "摄像头控制失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }

        // 麦克风开关
        view.findViewById<SwitchCompat>(R.id.switch_microphone)
            .setOnCheckedChangeListener { _, isChecked ->
                try {
                    if (isLiveStreaming) {
                        if (isChecked) {
                            mAlivcLivePusher.setMute(isChecked)

                        } else {
                            // 关闭麦克风 - 通过配置控制
                            mAlivcLivePusher.setMute(isChecked)
                        }
                    } else {
                        Toast.makeText(this, "请先开始直播", Toast.LENGTH_SHORT).show()
                        Log.w("LiveStreamActivity", "Cannot control microphone: not live streaming")
                    }
                } catch (e: Exception) {
                    Log.e("LiveStreamActivity", "Error controlling microphone: ${e.message}")
                    Toast.makeText(this, "麦克风控制失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }

        // 底部按钮点击事件
        view.findViewById<LinearLayout>(R.id.btn_lottery).setOnClickListener {
            val intent = Intent(this@LiveStreamActivity, LotteryActivity::class.java)
            intent.putExtra("roomId", mliveData?.id.toString())
            startActivity(intent)
            bottomSheetDialog?.dismiss()
        }

        view.findViewById<LinearLayout>(R.id.btn_coupon).setOnClickListener {
            val intent = Intent(this@LiveStreamActivity, CouponActivity::class.java)
            intent.putExtra("roomId", mliveData?.id.toString())

            startActivity(intent)
            bottomSheetDialog?.dismiss()
        }

        view.findViewById<LinearLayout>(R.id.btn_announcement).setOnClickListener {
            BottomSheetUtils.showAnnouncementBottomSheet(this) { content ->
                // 这里可以处理发布后的逻辑
                Toast.makeText(this, "发布公告: $content", Toast.LENGTH_SHORT).show()
                viewMode.pushLiveNotice("", content, mliveData?.id.toString())

            }
        }
        viewMode.PushLiveNoticeLV.observe(this@LiveStreamActivity) {
            if (it != null) {
                bottomSheetDialog?.dismiss()
            }
        }

        view.findViewById<LinearLayout>(R.id.btn_gift_forward).setOnClickListener {

            val intent = Intent(this@LiveStreamActivity, GiftEffectActivity::class.java)
            intent.putExtra("roomId", mliveData?.id.toString())
            startActivity(intent)
        }
    }

    @SuppressLint("MissingInflatedId")
    private fun showUserListDialog() {
        // 调用API获取用户列表数据
        viewMode.pageQuery(mliveData?.id.toString(), pageSize, currentPage)
        if (userListDialog == null) {
            userListDialog = BottomSheetDialog(this)
            val userListView = layoutInflater.inflate(R.layout.bottom_sheet_user_list, null)
            userListDialog?.setContentView(userListView)

            // 设置弹窗属性
            userListDialog?.setCancelable(true)
            userListDialog?.setCanceledOnTouchOutside(true)

            // 防止滑动关闭
            userListDialog?.behavior?.isDraggable = false
            userListDialog?.behavior?.isHideable = false

            tvDisableCount = userListView.findViewById<TextView>(R.id.tvDisableCount).apply {
                text = "禁言名单(${mLiveUserCount?.disableCount.toString()})"
            }
            tvBackName = userListView.findViewById<TextView>(R.id.tvBackName).apply {
                text = "踢出房间名单(${mLiveUserCount?.defriendCount.toString()})"
            }
            // 设置用户列表弹窗的控件监听
            setupUserListListeners(userListView)
        }

        userListDialog?.show()
    }

    @SuppressLint("CheckResult")
    private fun setupUserListListeners(view: View) {
        // 关闭按钮
        view.findViewById<ImageView>(R.id.iv_close_user_list).setOnClickListener {
            userListDialog?.dismiss()
        }

        // 设置点击外部关闭
        userListDialog?.setOnCancelListener {
            // 点击外部关闭
        }

        // 设置RecyclerView
        val recyclerView = view.findViewById<RecyclerView>(R.id.rv_user_list)
        recyclerView.layoutManager = LinearLayoutManager(this)

        // 设置滑动冲突处理
        recyclerView.isNestedScrollingEnabled = true
        recyclerView.overScrollMode = View.OVER_SCROLL_NEVER
        viewMode.PublishCouponLV.observe(this@LiveStreamActivity) {
            viewMode.liveUserCount(mliveData?.id.toString())

            // 刷新商品列表数据
            viewMode.pageQuery(mliveData?.id.toString(), pageSize, currentPage)

        }

        // 创建适配器（初始为空列表）
        val adapter = UserListAdapter(
            users = mutableListOf(), onUserAction = { user, action ->
                when (action) {
                    "mute" -> {
                        Toast.makeText(this, "禁言 ${user.name}", Toast.LENGTH_SHORT).show()
                        viewMode.userDisable(user.id)


                    }

                    "unmute" -> {
                        viewMode.userDisable(user.id)
                        Toast.makeText(this, "解除禁言 ${user.name}", Toast.LENGTH_SHORT).show()
                    }


                    "kick" -> {
                        viewMode.userDefriend(user.id)
//                        Toast.makeText(this, "踢出房间 ${user.name}", Toast.LENGTH_SHORT)
//                            .show()
                        view.findViewById<TextView>(R.id.tvBackName).apply {
                            text = "踢出房间名单(${mLiveUserCount?.defriendCount.toString()})"
                        }
                    }

                    "blacklist" -> {
                        viewMode.blacklist(user.id)
                        Toast.makeText(
                            this, "加入黑名单 ${user.name}", Toast.LENGTH_SHORT
                        ).show()

                    }

                }
            }, isMutedList = false
        )
        recyclerView.adapter = adapter

        // 观察API返回的数据
        viewMode.LiveUserListLV.observe(this@LiveStreamActivity) { liveUserList ->
            if (liveUserList != null && liveUserList.isNotEmpty()) {
                tvViewerCount.text = liveUserList.size.toString() + "人"
                if (liveUserList.isEmpty()) {
                    ivViewer1.visibility = View.GONE
                    ivViewer2.visibility = View.GONE
                    ivViewer3.visibility = View.GONE
                } else {
                    ivViewer1.apply {
                        Glide.with(this).load(liveUserList[0]?.avatar.toString())
                            .transform(RoundedCorners(50)).into(this)
                    }
                    if (liveUserList.size > 3) {
                        ivViewer2.apply {
                            Glide.with(this).load(liveUserList[1]?.avatar.toString())
                                .transform(RoundedCorners(50)).into(this)
                        }
                        ivViewer2.apply {
                            Glide.with(this).load(liveUserList[2]?.avatar.toString())
                                .transform(RoundedCorners(50)).into(this)
                        }
                    }

                }

                // 将API数据转换为User对象
                val users = mutableListOf<User>()


                // 转换API返回的LiveUserBean为User对象
                liveUserList.forEach { liveUser ->
                    val userRole = when (liveUser.userType) {
                        1 -> UserRole.ASSISTANT  // 助教
                        2 -> UserRole.ASSISTANT  // 销售
                        3 -> UserRole.VIEWER     // 外部用户
                        4 -> UserRole.VIEWER     // 虚拟用户
                        5 -> UserRole.STREAMER   // 主播
                        else -> UserRole.VIEWER
                    }

                    val user = User(
                        id = liveUser.id,
                        name = liveUser.userNick,
                        avatar = liveUser.avatar, // 默认头像，实际应该从API获取
                        role = userRole,
                        isMuted = liveUser.disable, // 是否禁言（禁言名单）
                        isKicked = liveUser.defriend, // 是否被踢出房间
                        isBlacklisted = liveUser.blacklist, // 是否被加入黑名单
                        joinTime = liveUser.joinTime // 加入时间
                    )
                    users.add(user)

                }

                // 更新适配器数据
                adapter.updateUsers(users)
            } else {
                // 如果API返回空数据，显示默认用户（主播）
                val defaultUsers = mutableListOf(
                    User(
                        getLocalUser()?.id.toString(),
                        getLocalUser()?.nickName.toString(),
                        getLocalUser()?.avatar.toString(),
                        UserRole.STREAMER
                    )
                )
                adapter.updateUsers(defaultUsers)
            }
        }

        // 观察禁言用户列表数据（移到外部，避免重复注册）
        viewMode.LiveDisableUserListLV.observe(this@LiveStreamActivity) { disableUserList ->
            if (disableUserList != null && disableUserList.isNotEmpty()) {
                // 将API数据转换为User对象
                val mutedUsers = disableUserList.map { liveUser ->
                    val userRole = when (liveUser.userType) {
                        1 -> UserRole.ASSISTANT  // 助教
                        2 -> UserRole.ASSISTANT  // 销售
                        3 -> UserRole.VIEWER     // 外部用户
                        4 -> UserRole.VIEWER     // 虚拟用户
                        5 -> UserRole.STREAMER   // 主播
                        else -> UserRole.VIEWER
                    }

                    User(
                        id = liveUser.id,
                        name = liveUser.userNick,
                        avatar = liveUser.avatar,
                        role = userRole,
                        isMuted = liveUser.disable,
                        isKicked = liveUser.defriend,
                        isBlacklisted = liveUser.blacklist,
                        joinTime = liveUser.joinTime
                    )
                }

                // 显示禁言名单弹窗
                BottomSheetUtils.showMutedListDialog(
                    context = this,
                    mutedUsers = mutedUsers,
                    onUnmuteUser = { user ->
                        // 调用解除禁言API
                        viewMode.userDisable(user.id)
                        ToastUtil.toastShortMessage("解除禁言: ${user.name}")
                    },
                    onUnmuteAll = {
                        // 批量解除禁言
                        mutedUsers.forEach { user ->
                            viewMode.userDisable(user.id)
                        }
                        ToastUtil.toastShortMessage("全部解禁")
                    })
            } else {
                // 如果没有禁言用户，显示空状态
                ToastUtil.toastShortMessage("暂无禁言用户")
            }
        }

        // 观察踢出用户列表数据（移到外部，避免重复注册）
        viewMode.LiveDefriendUserListLV.observe(this@LiveStreamActivity) { defriendUserList ->
            if (defriendUserList != null && defriendUserList.isNotEmpty()) {
                // 将API数据转换为User对象
                val kickedUsers = defriendUserList.map { liveUser ->
                    val userRole = when (liveUser.userType) {
                        1 -> UserRole.ASSISTANT  // 助教
                        2 -> UserRole.ASSISTANT  // 销售
                        3 -> UserRole.VIEWER     // 外部用户
                        4 -> UserRole.VIEWER     // 虚拟用户
                        5 -> UserRole.STREAMER   // 主播
                        else -> UserRole.VIEWER
                    }

                    User(
                        id = liveUser.id,
                        name = liveUser.userNick,
                        avatar = liveUser.avatar,
                        role = userRole,
                        isMuted = liveUser.disable,
                        isKicked = liveUser.defriend,
                        isBlacklisted = liveUser.blacklist,
                        joinTime = liveUser.joinTime
                    )
                }

                // 显示踢出名单弹窗
                BottomSheetUtils.showKickedListDialog(
                    context = this,
                    kickedUsers = kickedUsers,
                    onUnmuteUser = { user ->
                        // 调用恢复用户API
                        viewMode.userDefriend(user.id)
                        ToastUtil.toastShortMessage("恢复用户: ${user.name}")
                    },
                    onUnmuteAll = {
                        // 批量恢复用户
                        kickedUsers.forEach { user ->
                            viewMode.userDefriend(user.id)
                        }
                        ToastUtil.toastShortMessage("全部恢复")
                    })
            } else {
                // 如果没有踢出用户，显示空状态
                ToastUtil.toastShortMessage("暂无踢出用户")
            }
        }

        // 底部操作栏
        view.findViewById<View>(R.id.btn_muted_list).setOnClickListener {
            // 调用API获取禁言用户列表
            viewMode.pageQuery(mliveData?.id.toString(), pageSize, currentPage, disable = true)
        }

        //踢出黑名单
        view.findViewById<View>(R.id.btn_kicked_list).setOnClickListener {
            // 调用API获取踢出用户列表
            viewMode.pageQuery(mliveData?.id.toString(), pageSize, currentPage, defriend = true)
        }
    }

    private fun showProductListDialog() {
        refreshProductCountsInDialog()
        if (productListDialog == null) {
            productListDialog = BottomSheetDialog(this)


            val productListView = layoutInflater.inflate(R.layout.bottom_sheet_product_list, null)

            // 设置商品弹出框的高度
            val displayMetrics = resources.displayMetrics
            val screenHeight = displayMetrics.heightPixels
            val dialogHeight = (screenHeight * 0.7).toInt() // 设置为屏幕高度的70%

            val layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, dialogHeight
            )
            productListView.layoutParams = layoutParams

            productListDialog?.setContentView(productListView)

            // 设置弹窗属性
            productListDialog?.setCancelable(true)
            productListDialog?.setCanceledOnTouchOutside(true)

            // 设置商品列表弹窗的控件监听
            setupProductListListeners(productListView)
        }

        productListDialog?.show()
    }

    // 获取商品数量并更新标签页
    fun updateProductCounts() {
        // 获取售卖中商品数量
        viewMode.getOnSaleProductCount(mliveData?.id.toString() ?: "")
        viewMode.OnSaleProductCountLV.observe(this) { onSaleCount ->
            Log.d("xxxx", "售卖中商品数量: $onSaleCount")
            if (::tabOnSale.isInitialized) {
                tabOnSale.text = "售卖中 ($onSaleCount)"
            }
        }

        // 获取已下架商品数量
        viewMode.getOffShelfProductCount(mliveData?.id.toString() ?: "")
        viewMode.OffShelfProductCountLV.observe(this) { offShelfCount ->
            Log.d("xxxx", "已下架商品数量: $offShelfCount")
            if (::tabOffShelf.isInitialized) {
                tabOffShelf.text = "已下架 ($offShelfCount)"
            }
        }
    }

    private fun setupProductListListeners(view: View) {
        // ViewPager设置
        val viewPager = view.findViewById<androidx.viewpager2.widget.ViewPager2>(R.id.view_pager)
        val pagerAdapter = ProductPagerAdapter(this, mliveData?.id.toString() ?: "")
        viewPager.adapter = pagerAdapter

        // 标签页切换
        tabOnSale = view.findViewById<TextView>(R.id.tab_on_sale)
        tabOffShelf = view.findViewById<TextView>(R.id.tab_off_shelf)

        // 指示器
        val indicator1 = view.findViewById<View>(R.id.indicator_1)
        val indicator2 = view.findViewById<View>(R.id.indicator_2)
        updateProductCounts()

        // 显示售卖中商品
        fun showOnSaleProducts() {
            tabOnSale.setTextColor(getColor(R.color.black))
            tabOnSale.textSize = 16f
            tabOnSale.setTypeface(null, android.graphics.Typeface.BOLD)

            tabOffShelf.setTextColor(getColor(R.color.gray))
            tabOffShelf.textSize = 16f
            tabOffShelf.setTypeface(null, android.graphics.Typeface.NORMAL)

            viewPager.currentItem = 0

            // 更新指示器
            indicator1.setBackgroundResource(R.drawable.indicator_active)
            indicator2.setBackgroundResource(R.drawable.indicator_inactive)
        }

        // 显示已下架商品
        fun showOffShelfProducts() {
            tabOffShelf.setTextColor(getColor(R.color.blue_primary))
            tabOffShelf.textSize = 16f
            tabOffShelf.setTypeface(null, android.graphics.Typeface.BOLD)

            tabOnSale.setTextColor(getColor(R.color.gray))
            tabOnSale.textSize = 16f
            tabOnSale.setTypeface(null, android.graphics.Typeface.NORMAL)

            viewPager.currentItem = 1

            // 更新指示器
            indicator1.setBackgroundResource(R.drawable.indicator_inactive)
            indicator2.setBackgroundResource(R.drawable.indicator_active)
        }

        // 设置标签页点击事件
        tabOnSale.setOnClickListener {
            showOnSaleProducts()
        }

        tabOffShelf.setOnClickListener {
            showOffShelfProducts()
        }

        // ViewPager页面切换监听
        viewPager.registerOnPageChangeCallback(object :
            androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> showOnSaleProducts()
                    1 -> showOffShelfProducts()
                }
            }
        })

        // 获取商品数量并更新标签页
        updateProductCounts()

        // 默认显示售卖中商品
        showOnSaleProducts()

        // 搜索按钮点击事件
        val searchLayout = view.findViewById<LinearLayout>(R.id.search_layout)
        val switchShoppingCart = view.findViewById<SwitchCompat>(R.id.switch_shopping_cart)
        searchLayout.setOnClickListener {
            showSearchDialog()
        }
        //开关调用小黄车接口
        switchShoppingCart.setOnCheckedChangeListener { _, isChecked ->

            viewMode.closeOpenYellowCar()
        }
        if (mliveData?.isYellowCarEnabled == true) {
            switchShoppingCart.isChecked = false
        } else {
            switchShoppingCart.isChecked = true

        }
        // 设置点击外部关闭
        productListDialog?.setOnCancelListener {
            // 点击外部关闭
        }
    }

    private fun showSearchDialog() {
        if (searchDialog == null) {
            searchDialog = BottomSheetDialog(this)
            val searchView = LayoutInflater.from(this).inflate(R.layout.dialog_product_search, null)

            // 设置搜索弹出框的高度与商品弹出框一致
            val displayMetrics = resources.displayMetrics
            val screenHeight = displayMetrics.heightPixels
            val dialogHeight = (screenHeight * 0.7).toInt() // 设置为屏幕高度的70%

            val layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, dialogHeight
            )
            searchView.layoutParams = layoutParams

            searchDialog?.setContentView(searchView)

            // 设置弹窗属性
            searchDialog?.setCancelable(true)
            searchDialog?.setCanceledOnTouchOutside(true)

            // 获取搜索输入框
            val etSearch = searchView.findViewById<EditText>(R.id.et_search)

            etSearch.setOnEditorActionListener { v, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    val text = etSearch.text?.toString()?.trim().orEmpty()
                    viewMode.liveProductsPageQuery(
                        pageSize, currentPage, mliveData?.id.toString() ?: "", "", text
                    )

                    true

                } else {
                    false
                }
            }
            val tvResultCount = searchView.findViewById<TextView>(R.id.tv_result_count)
            val rvProduct = searchView.findViewById<RecyclerView>(R.id.rvProduct)
            val tvEmpty = searchView.findViewById<TextView>(R.id.tvEmpty)
            val ivBack = searchView.findViewById<ImageView>(R.id.ivBack)

            // 设置RecyclerView
            rvProduct.layoutManager = LinearLayoutManager(this)
            val searchAdapter = ProductListAdapter(mutableListOf(), true) { product, action ->
                // 处理搜索结果中的商品操作
                when (action) {
                    "view_product" -> {
                        // 显示商品详情
                        Toast.makeText(this, "查看商品: ${product.title}", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
            }
            rvProduct.adapter = searchAdapter

            // 观察搜索结果
            viewMode.liveProductBeanLV.observe(this) { result ->
                if (result?.rows != null && result.rows.isNotEmpty()) {
                    val productList = result.rows
                    searchAdapter.updateProducts(productList)
                    tvResultCount.text = "搜到${result.total}条相关数据"
                    rvProduct.visibility = View.VISIBLE
                    tvEmpty.visibility = View.GONE
                } else {
                    searchAdapter.updateProducts(emptyList())
                    tvResultCount.text = "搜到0条相关数据"
                    rvProduct.visibility = View.GONE
                    tvEmpty.visibility = View.VISIBLE
                }
            }

            // 搜索按钮
            searchView.findViewById<ImageView>(R.id.iv_search).setOnClickListener {
                val keyword = etSearch.text.toString().trim()
                if (keyword.isNotEmpty()) {
                    // 执行搜索
                    viewMode.liveProductsPageQuery(
                        pageSize, currentPage, mliveData?.id.toString() ?: "", "", keyword
                    )
                } else {
                    Toast.makeText(this, "请输入搜索关键词", Toast.LENGTH_SHORT).show()
                }
            }

            // 返回按钮
            ivBack.setOnClickListener {
                searchDialog?.dismiss()
            }

            // 设置点击外部关闭
            searchDialog?.setOnCancelListener {
                // 点击外部关闭
            }
        }

        searchDialog?.show()
    }


    private fun switchCamera(cameraId: String) {
        try {
            if (isLiveStreaming) {
                // 使用阿里云推流SDK切换摄像头
                mAlivcLivePusher.switchCamera()
                Log.d("LiveStreamActivity", "Switched camera to: $cameraId")
            } else {
                Log.w(
                    "LiveStreamActivity",
                    "Cannot switch camera: not live streaming or pusher not initialized"
                )
            }
        } catch (e: Exception) {
            Log.e("LiveStreamActivity", "Error switching camera: ${e.message}")
            Toast.makeText(this, "切换摄像头失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun toggleEmojiPanel() {
        if (isEmojiPanelVisible) {
            hideEmojiPanel()
        } else {
            showEmojiPanel()
        }
    }

    private fun showEmojiPanel() {
        // 收起系统键盘
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(etSend.windowToken, 0)

        if (emojiContainer == null) {
            val root = findViewById<ViewGroup>(android.R.id.content)
            val panelView = layoutInflater.inflate(R.layout.bottom_sheet_emoji, root, false)
            // 使用布局文件中定义的高度，而不是硬编码
            val panelHeight = (400 * resources.displayMetrics.density).toInt()
            val lp = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, panelHeight)
            lp.gravity = Gravity.BOTTOM
            panelView.layoutParams = lp

            // 设置数据
            val llMostUsed = panelView.findViewById<LinearLayout>(R.id.ll_most_used)
            val rvAllEmojis = panelView.findViewById<RecyclerView>(R.id.rv_all_emojis)
            val mostUsedEmojis = listOf(
                "\uD83D\uDE04",
                "\uD83D\uDE06",
                "\uD83D\uDE02",
                "\uD83E\uDD23",
                "\uD83D\uDE0D",
                "\uD83E\uDD70",
                "\uD83D\uDE0E",
                "\uD83E\uDD14",
            )
            val allEmojis = listOf(
                "😊",
                "😘",
                "🥺",
                "😠",
                "🤭",
                "😭",
                "😡",
                "😄",
                "😅",
                "😌",
                "😜",
                "😝",
                "🐕",
                "❤️",
                "🤏",
                "👏",
                "🙏",
                "🤗",
                "🌹",
                "😅",
                "🤩",
                "⭐",
                "👤",
                "🤔",
                "🥺",
                "🙂"
            )
            llMostUsed.removeAllViews()
            mostUsedEmojis.forEach { emoji ->
                val tv = TextView(this).apply {
                    text = emoji
                    textSize = 24f
                    gravity = Gravity.CENTER
                    setPadding(16, 16, 16, 16)
                    background = getDrawable(android.R.drawable.list_selector_background)
                    setOnClickListener {
                        insertEmojiToInput(emoji)
                        hideEmojiPanel()
                    }
                }
                val p = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
                p.setMargins(4, 4, 4, 4)
                llMostUsed.addView(tv, p)
            }
            rvAllEmojis.layoutManager = GridLayoutManager(this, 6)
            rvAllEmojis.adapter = EmojiAdapter(allEmojis) { emoji ->
                insertEmojiToInput(emoji)
                hideEmojiPanel()
            }
            // 强制RecyclerView重新测量和布局
            rvAllEmojis.requestLayout()
            // 添加到根布局
            root.addView(panelView)
            emojiContainer = panelView
        }

        // 上推输入栏到面板之上
        val panelHeight = (emojiContainer?.layoutParams?.height ?: 0)
        bottomControlPanel.animate().translationY(-panelHeight.toFloat()).setDuration(200)
            .setInterpolator(AccelerateDecelerateInterpolator()).start()
        emojiContainer?.visibility = View.VISIBLE
        isEmojiPanelVisible = true
    }

    private fun hideEmojiPanel() {
        emojiContainer?.let { view ->
            view.visibility = View.GONE
        }
        bottomControlPanel.animate().translationY(0f).setDuration(200)
            .setInterpolator(AccelerateDecelerateInterpolator()).start()
        isEmojiPanelVisible = false
    }

    /**
     * 将emoji插入到输入框
     */
    private fun insertEmojiToInput(emoji: String) {
        val currentText = etSend.text.toString()
        val cursorPosition = etSend.selectionStart
        val newText =
            currentText.substring(0, cursorPosition) + emoji + currentText.substring(cursorPosition)
        etSend.setText(newText)
        etSend.setSelection(cursorPosition + emoji.length)

        // 确保输入框获得焦点
        etSend.requestFocus()
    }

    // 刷新商品列表弹窗中的商品数量
    private fun refreshProductCountsInDialog() {
        // 延迟一下确保数据更新完成
        viewMode.getOnSaleProductCount(mliveData?.id.toString() ?: "")
        viewMode.getOffShelfProductCount(mliveData?.id.toString() ?: "")
    }


    private fun setupKeyboardHandling() {
        // 设置软键盘模式 - 调整布局大小
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

        // 监听软键盘状态变化
        val rootView = findViewById<View>(android.R.id.content)
        rootView.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            private var lastHeight = 0

            override fun onGlobalLayout() {
                val currentHeight = rootView.height
                if (lastHeight != 0 && currentHeight != lastHeight) {
                    val heightDifference = lastHeight - currentHeight
                    if (heightDifference > 200) {
                        // 软键盘弹出
                        Log.d("LiveStreamActivity", "Soft keyboard shown")
                        handleKeyboardShown()
                        // 键盘弹出时隐藏 emoji 面板，避免冲突
                        if (isEmojiPanelVisible) hideEmojiPanel()
                    } else if (heightDifference < -200) {
                        // 软键盘隐藏
                        Log.d("LiveStreamActivity", "Soft keyboard hidden")
                        handleKeyboardHidden()
                    }
                }
                lastHeight = currentHeight
            }
        })

        // 设置输入框焦点变化监听
        etSend.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                // 输入框获得焦点时，确保底部控制栏可见
                bottomControlPanel.post {
                    bottomControlPanel.requestLayout()
                }
            }
        }
    }

    private fun handleKeyboardShown() {
        // 软键盘弹出时的处理
        runOnUiThread {
            // 滚动弹幕列表到底部，确保最新消息可见
            rvDanmaku.post {
                rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
            }

            // 可以在这里添加其他UI调整
        }
    }

    private fun handleKeyboardHidden() {
        // 软键盘隐藏时的处理
        runOnUiThread {
            // 可以在这里添加其他UI调整
        }
    }

    // ==================== MQTT 相关方法 ====================

    private fun setupMqtt() {
        mqttManager = MqttManager.getInstance()
        mqttManager.addMessageCallback(this)

        val random6Digit = Random.nextInt(100000, 1000000)
        // 连接MQTT
        mqttManager.connect(
            this@LiveStreamActivity,
            "${mliveData?.liveRoomNo + "," + mliveData?.id + "," + getLocalUser()?.id + ",5" + "," + random6Digit}"
        ) { success, message ->
            runOnUiThread {
                if (success) {
                    Log.d("LiveStreamActivity", "MQTT connected: $message")

                    // 订阅直播相关主题
                    subscribeToLiveTopics()
                } else {
                    Log.e("LiveStreamActivity", "MQTT connection failed: $message")

                }
            }
        }
    }

    private fun subscribeToLiveTopics() {
        // 订阅直播相关主题
        val liveRoomNo = mliveData?.id ?: ""
        val topics = listOf(
            "chat/$liveRoomNo"
        )

        topics.forEach { topic ->
            mqttManager.subscribe(topic) { success, message ->
                runOnUiThread {
                    if (success) {
                        Log.d("LiveStreamActivity", "Subscribed to $topic")
                    } else {
                        Log.e("LiveStreamActivity", "Failed to subscribe to $topic: $message")
                    }
                }
            }
        }
    }

    // MQTT消息回调
    override fun onMessageReceived(topic: String, message: String) {

        runOnUiThread {
            handleLiveMessage(message)
        }
    }

    override fun onConnectionStatusChanged(connected: Boolean) {
        Log.d("LiveStreamActivity", "MQTT connection status changed: $connected")

    }


    private fun handleLiveMessage(message: String) {
        try {
            val gson = Gson()
            val chatMessage = gson.fromJson(message, MessageBean::class.java)

            when (chatMessage.type) {
                1 -> { /* JOIN(1) - 进入房间 */
                }

                2 -> { /* LEAVE(2) - 离开房间 */
                }

                3 -> { // MSG(3) - 普通消息
                    // 添加到弹幕适配器
                    Log.d("xxxx", "chatMessage=======>$chatMessage")
                    if (chatMessage.range == 0) {
                        danmakuAdapter.append(chatMessage)
                        // 滚动到最新消息
                        rvDanmaku.post {
                            rvDanmaku.scrollToPosition(danmakuAdapter.itemCount - 1)
                        }
                    }

                }

                4 -> { /* SYSTEM(4) - 系统消息 */
                }

                5 -> { /* DRAW(5) - 抽奖倒计时 */
                }

                6 -> { /* COUPON(6) - 优惠券倒计时 */
                }

                7 -> { /* TAUGHT(7) - 商品讲解 */
                }

                8 -> { /* NOTICE(8) - 公告 */
                }

                9 -> { /* COUPON_RECEIVE(9) - 优惠券领取 */
                }

                10 -> { /* DRAW_USER(10) - 抽奖完成通知 */
                }

                11 -> { /* MSG_CONCEAL(11) - 消息隐藏 */
                }

                12 -> { /* BESTOW_GIFT(12) - 赠送礼物 */

                    llGift.visibility = View.VISIBLE
                    val gson = Gson()
                    val giftData = gson.fromJson(chatMessage.content, GiftData::class.java)
                    tvGiftName.text = giftData.nickName + "赠送了一个" + giftData.giftName
                    ivGiftIcon.apply {
                        Glide.with(this).load(giftData.effectUrl).into(this)
                    }
                    llGift.postDelayed({
                        llGift.visibility = View.GONE
                    }, 5000)
                }

                13 -> { /* DEFRIEND(13) - 踢出直播间 */
                }

                14 -> { /* POINTS_ACQUISITION(14) - 获取积分 */
                }

                15 -> { /* CANCEL_TAUGHT(15) - 取消讲解 */
                }

                16 -> { /* LIKE(16) - 点赞 */
                    tvStreamerNumber.text = chatMessage.content.toString() + "点赞"

                }

                17 -> { /* PUTAWAY(17) - 商品上架 */
                }

                18 -> { /* CONFIG_STATUS_UPDATE(18) - 直播配置状态更新 */

                    viewMode.getLiveData()
                }

                19 -> { /* THE_USER_IS_BUYING(19) - 正在购买商品 */
                }

                20 -> { /* POPULARITY(20) - 直播间人气推送 */
                    Log.d("xxxx", "=======${chatMessage.content}")
                    val gson = Gson()
                    val liveStats = gson.fromJson(chatMessage.content, LiveStats::class.java)
                    tvViewerCount.text = liveStats.liveCount.toString() + "人"
                }

                26 -> {
                    viewMode.getLiveInfo()
                }

                else -> { /* 未知类型 */
                }
            }

        } catch (e: JsonSyntaxException) {
            Log.e("LiveStreamActivity", "Error parsing JSON message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        } catch (e: Exception) {
            Log.e("LiveStreamActivity", "Error handling message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        }
    }

    // 发送直播状态到MQTT
    private fun publishLiveStatus(status: String) {
        try {
            if (!::mqttManager.isInitialized || !mqttManager.isConnected()) {
                Log.w("LiveStreamActivity", "MQTT not available for publishing status: $status")
                return
            }

            val liveRoomNo = mliveData?.liveRoomNo ?: ""
            val message = """
                {
                    "status": "$status",
                    "liveRoomNo": "$liveRoomNo",
                    "timestamp": ${System.currentTimeMillis()},
                    "device": "android"
                }
            """.trimIndent()

            mqttManager.publish("live/$liveRoomNo/status", message) { success, result ->
                Log.d("LiveStreamActivity", "Publish live status result: $success, $result")
            }
        } catch (e: Exception) {
            Log.e("LiveStreamActivity", "Error publishing live status: ${e.message}")
        }
    }


    override fun onDestroy() {
        super.onDestroy()

        // 停止风险提示文本滚动
        stopRiskAlertScroll()

        // 移除MQTT回调（如果已初始化）
        try {
            if (::mqttManager.isInitialized) {
                mqttManager.removeMessageCallback(this)

                // 发送直播结束状态
                publishLiveStatus("ended")
            }
        } catch (e: Exception) {
            Log.e("LiveStreamActivity", "Error in MQTT cleanup: ${e.message}")
        }

        // 确保停止摄像头预览
        try {
            if (isLiveStreaming) {
                isLiveStreaming = false
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // ======= 权限相关（恢复） =======
    private fun checkCameraPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this, Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestCameraPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO),
            CAMERA_PERMISSION_REQUEST
        )
    }

    private fun checkMicrophonePermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this, Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST) {
            val grantedAll =
                grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (!grantedAll) {
                Toast.makeText(this, "需要摄像头权限才能开启直播", Toast.LENGTH_SHORT).show()
                return
            }
            // 权限已授予，若存在等待启动则触发
            if (pendingStartPush) {
                try {
                    mAlivcLivePusher.startPreview(surfaceView)
                    if (!mliveData?.pushLiveUrl.isNullOrEmpty()) {
                        surfaceView.postDelayed({
                            try {
                                mAlivcLivePusher.startPush(mliveData?.pushLiveUrl)
                            } catch (_: Exception) {
                            }
                        }, 150)
                    }
                } catch (_: Exception) {
                } finally {
                    pendingStartPush = false
                }
            }
        }
    }

    // 以16:9为目标比例做center-crop，避免画面拉伸
    private fun adjustSurfaceFixedSize(viewWidth: Int, viewHeight: Int) {
        if (viewWidth <= 0 || viewHeight <= 0) return

        // 获取摄像头支持的预览尺寸
        val cameraManager =
            getSystemService(Context.CAMERA_SERVICE) as android.hardware.camera2.CameraManager
        val cameraId = "1" // 默认前置摄像头

        try {
            val characteristics = cameraManager.getCameraCharacteristics(cameraId)
            val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)

            if (map != null) {
                val previewSizes = map.getOutputSizes(android.graphics.SurfaceTexture::class.java)
                if (previewSizes.isNotEmpty()) {
                    // 选择最接近16:9比例的预览尺寸
                    val targetRatio = 16f / 9f
                    var bestSize = previewSizes[0]
                    var minDiff = Float.MAX_VALUE

                    for (size in previewSizes) {
                        val ratio = size.width.toFloat() / size.height.toFloat()
                        val diff = Math.abs(ratio - targetRatio)
                        if (diff < minDiff) {
                            minDiff = diff
                            bestSize = size
                        }
                    }

                    // 使用选中的预览尺寸设置Surface
                    try {
                        surfaceHolder.setFixedSize(bestSize.width, bestSize.height)
                        Log.d("Camera", "Set surface size: ${bestSize.width}x${bestSize.height}")
                        return
                    } catch (e: Exception) {
                        Log.e("Camera", "Failed to set surface size: ${e.message}")
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("Camera", "Error getting camera characteristics: ${e.message}")
        }

        // 如果无法获取摄像头预览尺寸，使用默认的16:9比例计算
        val targetRatio = 16f / 9f
        val viewRatio = viewWidth.toFloat() / viewHeight.toFloat()

        var bufferWidth: Int
        var bufferHeight: Int
        if (viewRatio > targetRatio) {
            // 视图更"宽"，以高度为基准计算宽度
            bufferHeight = viewHeight
            bufferWidth = (bufferHeight * targetRatio).toInt()
        } else {
            // 视图更"高"，以宽度为基准计算高度
            bufferWidth = viewWidth
            bufferHeight = (bufferWidth / targetRatio).toInt()
        }

        if (bufferWidth > 0 && bufferHeight > 0) {
            try {
                surfaceHolder.setFixedSize(bufferWidth, bufferHeight)
                Log.d("Camera", "Set fallback surface size: ${bufferWidth}x${bufferHeight}")
            } catch (e: Exception) {
                Log.e("Camera", "Failed to set fallback surface size: ${e.message}")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 启动定时查询
        startPeriodicQuery()
    }

    override fun onPause() {
        super.onPause()
        // 停止定时查询
        stopPeriodicQuery()
    }

    private fun startPeriodicQuery() {
        queryJob = CoroutineScope(Dispatchers.IO).launch {
            while (isActive) {
                // 执行查询
                viewMode.pageQuery(mliveData?.id.toString(), pageSize, currentPage)

                // 等待30秒
                delay(30000)
            }
        }
    }

    private fun stopPeriodicQuery() {
        queryJob?.cancel()
        queryJob = null
    }

    // ==================== 风险提示文本相关方法 ====================


    private fun updateRiskAlertDisplay() {


        riskAlertTextView.text = riskAlertText
        riskAlertTextView.textSize = displayFontSize
        riskAlertTextView.setTextColor(android.graphics.Color.parseColor(displayFontColour))
        riskAlertTextView.alpha = displayTransparency
        riskAlertTextView.visibility = View.VISIBLE


        riskAlertTextView.bringToFront()
        riskAlertTextView.elevation = 20f
        riskAlertTextView.visibility = View.VISIBLE


        // 清除可能影响 y 定位的顶部 margin（不依赖具体父布局类型）
        (riskAlertTextView.layoutParams as? ViewGroup.MarginLayoutParams)?.let { lp ->
            if (lp.topMargin != 0) {
                lp.topMargin = 0
                riskAlertTextView.layoutParams = lp
            }
        }

        // 根据显示模式启动滚动（强制按当前需求使用全屏行滚动）
        Log.d("RiskAlert", "=== 准备启动滚动，displayMode = $displayMode（强制按2处理） ===")
        when (displayMode) {
            1 -> {
                Log.d("RiskAlert", "Starting bottom scroll (单行循环滚动)")
                startBottomScroll()
            }

            2 -> {
                Log.d("RiskAlert", "Starting full screen scroll (5行滚动)")
                startFullScreenScroll()
            }

            else -> {
                // 强制全屏行滚动
                startFullScreenScroll()
            }
        }
    }

    private fun startBottomScroll() {
        stopRiskAlertScroll()
        riskAlertScrollJob = CoroutineScope(Dispatchers.Main).launch {
            val textView = riskAlertTextView
            val text = textView.text.toString()
            val textWidth = textView.paint.measureText(text)
            val screenWidth = textView.context.resources.displayMetrics.widthPixels


            // 调整滚动速度，确保不会太快
            val scrollSpeed = if (displayScrollSpeed < 10) 50 else displayScrollSpeed


            var currentX = -textWidth.toFloat() // 从左边开始

            while (isActive) {
                textView.translationX = currentX
                currentX += 1f // 每次移动1像素，从左往右

                if (currentX >= screenWidth) {
                    currentX = -textWidth.toFloat() // 回到左边重新开始
                    // 滚动完成后，停留一下再重新开始
                    delay(2000) // 停留2秒
                }

                delay(scrollSpeed.toLong())
            }
        }
    }

    private fun startFullScreenScroll() {
        stopRiskAlertScroll()
        riskAlertScrollJob = CoroutineScope(Dispatchers.Main).launch {
            val textView = riskAlertTextView
            val text = textView.text.toString()

            // 使用根布局高度，计算可容纳的“行数”（按 TextView 实际高度划分）
            val rootView = findViewById<View>(android.R.id.content)
            val containerHeight = (rootView.height.takeIf { it > 0 }
                ?: textView.context.resources.displayMetrics.heightPixels)

            // 确保拿到 TextView 的高度
            var tvHeight = textView.height
            if (tvHeight <= 0) {
                textView.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                )
                tvHeight = textView.measuredHeight
            }
            if (tvHeight <= 0) {
                // 兜底：用字体大小粗略估算行高
                tvHeight = (displayFontSize * resources.displayMetrics.density * 1.8f).toInt()
                    .coerceAtLeast(1)
            }
            // 按需求固定分成5行显示，更符合期望效果
            val rows = 5
            val lineHeightPx = containerHeight / rows.toFloat()
            Log.d(
                "RiskAlert",
                "Full screen scroll started, containerHeight=$containerHeight, tvHeight=$tvHeight, rows=$rows, lineHeightPx=$lineHeightPx"
            )

            // 调整滚动速度
            val scrollSpeed = if (displayScrollSpeed < 10) 50 else displayScrollSpeed
            Log.d("RiskAlert", "Adjusted scroll speed: $scrollSpeed")

            var rowIndex = 0
            val screenWidth = textView.context.resources.displayMetrics.widthPixels

            while (isActive) {
                // 计算当前行的Y坐标（行中心对齐到该行区域中部）
                // 将 TextView 垂直居中到该行区域内
                val rowTop = rowIndex * lineHeightPx
                val centeredTop = (rowTop + (lineHeightPx - tvHeight) / 2f)
                val clampedY = centeredTop.coerceIn(
                    0f, (containerHeight - tvHeight).toFloat().coerceAtLeast(0f)
                )
                Log.d("RiskAlert", "=== 显示第${rowIndex + 1}/$rows 行，y=$clampedY ===")

                // 将 TextView 移到该行
                textView.y = clampedY
                textView.translationX = 0f

                // 计算文本宽度
                val textWidth = textView.paint.measureText(text)
                Log.d(
                    "RiskAlert",
                    "行${rowIndex + 1} - textWidth=$textWidth, screenWidth=$screenWidth"
                )

                // 水平滚动：从左完全外到右完全外
                var currentX = -textWidth.toFloat()
                val endX = screenWidth.toFloat()
                while (isActive && currentX < endX) {
                    textView.translationX = currentX
                    currentX += 1f
                    delay(scrollSpeed.toLong())
                }
                textView.translationX = 0f
                Log.d("RiskAlert", "行${rowIndex + 1} 滚动完成")

                // 切换到下一行；到达底部后回到顶部
                rowIndex = (rowIndex + 1) % rows
                delay(500)
            }
        }
    }

    private fun stopRiskAlertScroll() {
        riskAlertScrollJob?.cancel()
        riskAlertScrollJob = null
        riskAlertTextView.translationX = 0f
    }


}